package com.observatory.baapp;

import android.app.Activity;
import android.app.Application;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;

import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;

import cn.asus.push.BuildConfig;
import cn.jpush.android.api.JPushInterface;

public class MyApp extends Application {
    private int activityCount = 0;
    @Override
    public void onCreate() {
        super.onCreate();
        // 确保在主线程初始化
        Handler mainHandler = new Handler(Looper.getMainLooper());
        mainHandler.post(() -> {
            // 只保留一次初始化调用
            if (BuildConfig.DEBUG) {
                JPushInterface.setDebugMode(true);
            } else {
                JPushInterface.setDebugMode(false);
            }

            JPushInterface.init(this); // 关键初始化

            Set<Integer> pushDays = new HashSet<>(Arrays.asList(0, 1, 2, 3, 4, 5, 6));
            JPushInterface.setPushTime(this, pushDays, 0, 23);
            JPushInterface.setSilenceTime(this, 0, 0, 23, 59);

            // 移除内层的mainHandler.post(...)
        });

        registerActivityLifecycleCallbacks(new ActivityLifecycleCallbacks() {
            @Override
            public void onActivityCreated(Activity activity, Bundle savedInstanceState) {}

            @Override
            public void onActivityStarted(Activity activity) {}

            @Override
            public void onActivityResumed(Activity activity) {
                activityCount++;
                Log.d("AppState", "Activity Resumed. Count: " + activityCount);
            }

            @Override
            public void onActivityPaused(Activity activity) {
                activityCount--;
                Log.d("AppState", "Activity Paused. Count: " + activityCount);
                // 确保计数不为负数
                if (activityCount < 0) activityCount = 0;
            }

            @Override
            public void onActivityStopped(Activity activity) {}

            @Override
            public void onActivitySaveInstanceState(Activity activity, Bundle outState) {}

            @Override
            public void onActivityDestroyed(Activity activity) {}
        });
    }

    public boolean isAppInForeground() {
        Log.d("AppState", "Foreground Check: " + (activityCount > 0));
        return activityCount > 0;
    }

}
